package com.ugoodtech.mdcc.client.controller;

/* Copyright (C) Ugoodtech, Inc - All Rights Reserved.
 * Unauthorized copying of this file, via any medium is strictly prohibited.
 * Proprietary and confidential.
 * Written by Stone Shaw.
 */

import com.alibaba.fastjson.JSON;
import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.ComplaintFollowUser;
import com.ugoodtech.mdcc.client.dto.GroupResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.dto.LabelValue;
import com.ugoodtech.mdcc.client.service.QuestionService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "question接口")
@RestController
@RequestMapping("/question")
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private StationCustomerReportRepository stationCustomerReportRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private StationPaintReportRepository stationPaintReportRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private NationRepository nationRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private ComplaintReportDataRepository complaintReportDataRepository;

    @Autowired
    private ComplaintSolutionDataRepository complaintSolutionDataRepository;

    private static Logger logger = LoggerFactory.getLogger(QuestionController.class);



    @ApiOperation("获取筛选的条件--该维修站是否使用我司增值服务")
    @RequestMapping(value = "/getPayService", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getPayService() {
        return questionService.getPayService();
    }

    @ApiOperation("获取筛选的条件--油漆配送时效")
    @RequestMapping(value = "/getSentTime", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getSentTime() {
        return questionService.getSentTime();
    }

    @ApiOperation("获取筛选的条件--经销商上门服务周期")
    @RequestMapping(value = "/getServiceTime", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getServiceTime() {
        return questionService.getServiceTime();
    }

    @ApiOperation("获取筛选的条件--常规报告状态")
    @RequestMapping(value = "/getReportStatus", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getReportStatus() {
        return questionService.getReportStatus();
    }

    @ApiOperation("获取筛选的条件--常规报告中的服务项目")
    @RequestMapping(value = "/getServiceTarget", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getServiceTarget() {
        return questionService.getServiceTarget();
    }


    @ApiOperation("获取章节列表")
    @RequestMapping(value = "/getSections", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getSections(Principal principal,
                                    @ApiParam("分类") @RequestParam(required = false) QuestionPaper.QuestionPaperCategory category,
                                    @ApiParam("用户身份") @RequestParam(required = false) Integer owner,
                                    @ApiParam("是否创建报告") @RequestParam(required = false) Boolean isCreate
    ) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        if (isCreate != null && isCreate) {
            if ((category.equals(QuestionPaper.QuestionPaperCategory.colorReport) || category.equals(QuestionPaper.QuestionPaperCategory.serviceReport)) && owner == null) {
                return JsonResponse.errorResponseWithError("抱歉", "请先选择身份");
            }
        }
        List<QuestionSection> questionSections = questionService.getQuestionSections(category,owner);
        return JsonResponse.successResponseWithData(questionSections);
    }

    private List<StationCustomerReport> customerReports = null;
    private List<StationRegularServiceReport> regularServiceReports = null;
    private List<StationColorReport> colorReports = null;
    private List<StationPaintReport> paintReports = null;
    private List<ComplaintReportData> complaintReportDataList = null;
    private List<ComplaintSolutionData> complaintSolutionDataList = null;


    @ApiOperation("获取章节分组和题目")
    @RequestMapping(value = "/getGroups", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getGroups(
//            Principal principal,
            @ApiParam("章节id") @RequestParam(required = false) Long sectionId,
            @ApiParam("报告id") @RequestParam(required = false) Long reportId,
            @ApiParam("用户身份") @RequestParam(required = false) Integer owner,
            @ApiParam("报告类型:service_report,techcolor_report,paint_report,complaint_report,complaint_solution_report") @RequestParam(required = false) String reportType,
            @ApiParam("补充基础报告维修站id") @RequestParam(value = "temporaryStationId", required = false) Long stationId,
            @ApiParam("重复编辑精益板喷维修站id") @RequestParam(value = "stationId", required = false) Long paintStationId
    ) {
//        if (principal == null) {
//            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
//        }
//        User clientUser = userRepository.findByUsername(principal.getName());
//        if (clientUser == null) {
//            return JsonResponse.errorResponseWithError("500", "未找到此用户");
//        }
        if (stationId != null && stationId != 0 && reportType.equals(Constants.TECHCOLOR_REPORT)) {
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.station.id.eq(stationId));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            StationReport stationReport = stationReportRepository.findOne(builder);
            if (stationReport != null) {
                reportId = stationReport.getId();
            }
        }

        if (paintStationId != null && paintStationId != 0 && reportType.equals(Constants.PAINT_REPORT)) {
            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.station.id.eq(paintStationId));
            builder.and(qStationReport.category.eq(Constants.PAINT_REPORT));
            List<StationReport> stationReport = (List<StationReport>) stationReportRepository.findAll(builder);
            if (stationReport != null && stationReport.size() != 0) {
                reportId = stationReport.get(stationReport.size() - 1).getId();
            }
        }

        logger.info("开始调用此方法");
        Long time = System.currentTimeMillis();
        if (reportId != null && reportId != 0) {
            if (reportType.equals(Constants.CUSTOMER_REPORT)) {
                customerReports = stationCustomerReportRepository.selectAnswer(reportId);
            }
            if (reportType.equals(Constants.SERVICE_REPORT)) {
                regularServiceReports = stationRegularServiceReportRepository.selectAnswer(reportId);
            }
            if (reportType.equals(Constants.TECHCOLOR_REPORT)) {
                colorReports = stationColorReportRepository.selectAnswer(reportId);
            }
            if (reportType.equals(Constants.PAINT_REPORT)) {
                paintReports = stationPaintReportRepository.selectAnswer(reportId);
            }
            if (reportType.equals(Constants.COMPLAINT_REPORT)) {
                complaintReportDataList = complaintReportDataRepository.selectAnswer(reportId);
            }
            if (reportType.equals(Constants.COMPLAINT_SOLUTION_REPORT)) {
                complaintSolutionDataList = complaintSolutionDataRepository.selectAnswer(reportId);
            }
        }
        List<QuestionGroup> questionGroups = questionService.getQuestions(sectionId,owner);
        List<Object> dataList = new ArrayList<>();
        for (QuestionGroup questionGroup : questionGroups) {
            dataList.add(GroupResponse.turnGroupToResponse(questionGroup));
            List<Question> questionGroupList = questionService.getQuestionsByGroup(questionGroup.getId(),owner);
            for (Question question : questionGroupList) {
                if (null != owner && question.getOwner() != owner && question.getOwner()!=2){
                    continue;
                }
                Long question_id = Long.valueOf(question.getId());
                if (question_id == 146 || question_id == 147 || question_id == 148 || question_id == 149 || question_id == 150 || question_id == 151 ||
                        question_id == 152 || question_id == 153 || question_id == 154) {
                    continue;
                }
                if (reportId != null && reportId != 0) {
                    question = selectAnswer(question, reportId);
                }

                List<QuestionAnswerOption> questionAnswerOptions = questionService.getOptionsByGroup(question.getId(),owner);
                question.setOptions(questionAnswerOptions);
                List<Question> questions = new ArrayList<>();
                questions.add(question);
                if (QuestionCategory.TEXT.equals(question.getCategory())) {
                    Map<String, Object> textQuestion = new HashMap<>();
                    textQuestion.put("category", question.getCategory().name());
                    textQuestion.put("required", Boolean.valueOf(question.getRequired()));
                    textQuestion.put("type", "question");
                    textQuestion.put("inputList", questions);
                    dataList.add(textQuestion);
                } else {
                    dataList.add(question);
                }
            }
        }

        In excel = new QuestionController().new In();
        if (sectionId == 10) {
            excel.setExcel(true);
            dataList.add(excel);
        } else {

            dataList.add(excel);
        }

        customerReports = null;
        regularServiceReports = null;
        colorReports = null;
        paintReports = null;
        complaintReportDataList = null;
        complaintSolutionDataList = null;
        logger.info("调用完毕");
        logger.info("总耗时：" + (System.currentTimeMillis() - time));
        return JsonResponse.successResponseWithData(dataList);
    }

    //内部类
    class In {
        private boolean excel = false;

        private Long reportId;

        public boolean isExcel() {
            return excel;
        }

        public void setExcel(boolean excel) {
            this.excel = excel;
        }
    }


    private Question selectAnswer(Question question, Long report_id) {
        if (complaintSolutionDataList != null) {
            for (ComplaintSolutionData report : complaintSolutionDataList) {
                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else if (StringUtils.isNotEmpty(report.getAnswerOther2())) {
                        question.setAnswer_other2(report.getAnswerOther2());
                    } else {
                        question.setAnswer_other("");
                        question.setAnswer_other2("");
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerId())) {
                        if (report.getAnswerId().indexOf(",") != -1) {
                            question.setSelected(report.getAnswerId());
                        } else if (report.getAnswerId() != null && Long.valueOf(report.getAnswerId()) != 0) {
                            question.setSelected(report.getAnswerId());
                        } else {
                            question.setSelected("");
                        }
                        if (report.getAnswerId().equals("444")) {
                            if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                                List<ComplaintFollowUser> followUserList = new ArrayList<>();
                                for (String userId : report.getAnswerOther().split(",")) {
                                    UserProfile userProfile = userProfileRepository.findByUserId(Long.valueOf(userId));
                                    if (null != userProfile && StringUtils.isNotEmpty(userProfile.getRealName())) {
                                        ComplaintFollowUser followUser = new ComplaintFollowUser(Long.valueOf(userId), userProfile.getRealName());
                                        followUserList.add(followUser);
                                    }
                                }
                                question.setAnswer_other(JSON.toJSONString(followUserList));
                            } else if (StringUtils.isNotEmpty(report.getAnswerOther2()) && report.getAnswerOther2().indexOf(",") == -1) {
                                UserProfile userProfile = userProfileRepository.findByUserId(Long.valueOf(report.getAnswerOther2()));
                                ComplaintFollowUser followUser = new ComplaintFollowUser(Long.valueOf(report.getAnswerOther2()), userProfile.getRealName());
                                question.setAnswer_other2(JSON.toJSONString(followUser));
                            }
                        }
                    }
                }
            }
            return question;
        }

        if (complaintReportDataList != null) {
            for (ComplaintReportData report : complaintReportDataList) {
                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerId())) {
                        if (report.getAnswerId().indexOf(",") != -1) {
                            question.setSelected(report.getAnswerId());
                        } else if (report.getAnswerId() != null && Long.valueOf(report.getAnswerId()) != 0) {
                            question.setSelected(report.getAnswerId());
                        } else {
                            question.setSelected("");
                        }
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (report.getQuestionId() == 194L) {
                        StringBuffer stringBuffer = new StringBuffer("");
                        if (StringUtils.isNotEmpty(report.getAnswerId())) {
                            String[] ids = report.getAnswerId().split(",");
                            for (String id : ids) {
                                if (StringUtils.isNotEmpty(id)) {
                                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                                    if (answerOption != null && StringUtils.isNotEmpty(answerOption.getName())) {
                                        stringBuffer.append(answerOption.getName() + ",");
                                    }
                                }
                            }
                        }
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            question.setAnswer_other2(report.getAnswerOther());
                        }
                        question.setAnswer_other(stringBuffer.toString());
                    }
                }
            }
            return question;
        }
        if (customerReports != null) {
            for (StationCustomerReport report : customerReports) {
                if (question.getId().equals(report.getQuestionId())) {
                    QuestionAnswerOption answer = questionAnswerOptionRepository.findOne(Long.valueOf(report.getAnswerId()));
                    if (answer != null && StringUtils.isNotEmpty(answer.getName())) {
                        question.setAnswer_other(answer.getName());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerPhoto())) {
                        question.setAnswer_photo(report.getAnswerPhoto());
                    } else {
                        question.setAnswer_photo("");
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerId())) {
                        if (report.getAnswerId().indexOf(",") != -1) {
                            question.setSelected(report.getAnswerId());
                        } else if (Long.valueOf(report.getAnswerId()) != 0) {
                            question.setSelected(report.getAnswerId());
                        } else {
                            question.setSelected("");
                        }
                    } else {
                        question.setSelected("");
                    }
                }
            }
            return question;
        }

        if (regularServiceReports != null) {
            for (StationRegularServiceReport report : regularServiceReports) {
                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (report.getQuestionId() == 155L) {
                        QStationReport qStationReport = QStationReport.stationReport;
                        BooleanBuilder builder = new BooleanBuilder();
                        builder.and(qStationReport.deleted.eq(false));
                        builder.and(qStationReport.enabled.eq(true));
                        builder.and(qStationReport.id.eq(report_id));
                        StationReport stationReport = stationReportRepository.findOne(builder);
                        if (stationReport != null && StringUtils.isNotEmpty(stationReport.getAnswerOther())) {
                            question.setAnswer_other2(stationReport.getAnswerOther());
                        }
                    }
                    if (report.getQuestionId() == 156L) {
                        QStationReport qStationReport = QStationReport.stationReport;
                        BooleanBuilder builder = new BooleanBuilder();
                        builder.and(qStationReport.deleted.eq(false));
                        builder.and(qStationReport.enabled.eq(true));
                        builder.and(qStationReport.id.eq(report_id));
                        StationReport stationReport = stationReportRepository.findOne(builder);
                        if (stationReport != null && StringUtils.isNotEmpty(stationReport.getDeparmentIds())) {
                            String[] parentUserIds = stationReport.getDeparmentIds().split(",");
                            StringBuffer stringBuffer = new StringBuffer();
                            for (String id : parentUserIds) {
                                Department department = null;
                                if (StringUtils.isNotEmpty(id)) {
                                    stringBuffer.append((id + ","));
//                                    department = departmentRepository.findOne(Long.valueOf(id));
//                                }
//                                if (department != null) {
//                                    stringBuffer.append((department.getTotalName() + ","));
                                }
                            }
                            String str = stringBuffer.toString();
                            if (StringUtils.isNotEmpty(stringBuffer.toString())) {
                                str = str.substring(0, str.length() - 1);
                            }
                            question.setAnswer_other(str);
                        }
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerPhoto())) {
                        question.setAnswer_photo(report.getAnswerPhoto());
                    } else {
                        question.setAnswer_photo("");
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerId()) && report.getAnswerId().indexOf(",") != -1) {
                        question.setSelected(report.getAnswerId());
                    } else if (StringUtils.isNotEmpty(report.getAnswerId()) && Long.valueOf(report.getAnswerId()) != 0) {
                        question.setSelected(report.getAnswerId());
                    } else {
                        question.setSelected("");
                    }
                }
            }
            return question;
        }

        if (colorReports != null) {
            for (StationColorReport report : colorReports) {
                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (report.getQuestionId() == 173) {
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            Nation nation = nationRepository.selectByProvince(report.getAnswerOther());
                            if (nation == null) {
                                question.setAnswer_other("");
                            } else {
                                question.setAnswer_other(nation.getProvince());
                            }
                        }
                    }
                    if (report.getQuestionId() == 174) {
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            List<Nation> nationList = nationRepository.selectByCity(report.getAnswerOther());
                            Nation nation = CollectionUtils.isEmpty(nationList) ? null : nationList.get(0);
                            if (nation == null) {
                                question.setAnswer_other("");
                            } else {
                                question.setAnswer_other(nation.getCity());
                            }
                        }
                    }
                    if (report.getQuestionId() == 8L) {
                        StringBuffer stringBuffer = new StringBuffer("");
                        if (StringUtils.isNotEmpty(report.getAnswerId())) {
                            String[] ids = report.getAnswerId().split(",");
                            for (String id : ids) {
                                if (StringUtils.isNotEmpty(id)) {
                                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                                    if (answerOption != null && StringUtils.isNotEmpty(answerOption.getName())) {
                                        stringBuffer.append(answerOption.getName() + ",");
                                    }
                                }
                            }
                        }
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            question.setAnswer_other2(report.getAnswerOther());
                        }
                        question.setAnswer_other(stringBuffer.toString());
                    }

                    if (StringUtils.isNotEmpty(report.getAnswerPhoto())) {
                        question.setAnswer_photo(report.getAnswerPhoto());
                    } else {
                        question.setAnswer_photo("");
                    }
                    if (report.getAnswerId() != null && report.getAnswerId().indexOf(",") != -1) {
                        question.setSelected(report.getAnswerId());
                    } else if (StringUtils.isNotEmpty(report.getAnswerId()) && Long.valueOf(report.getAnswerId()) != 0) {
                        question.setSelected(report.getAnswerId());
                    } else {
                        question.setSelected("");
                    }
                }
            }
            return question;
        }

        if (paintReports != null) {
            for (StationPaintReport report : paintReports) {

                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerPhoto())) {
                        question.setAnswer_photo(report.getAnswerPhoto());
                    } else {
                        question.setAnswer_photo("");
                    }
                    if (report.getAnswerId() != null && report.getAnswerId().indexOf(",") != -1) {
                        question.setSelected(report.getAnswerId());
                    } else if (StringUtils.isNotEmpty(report.getAnswerId()) && Long.valueOf(report.getAnswerId()) != 0) {
                        question.setSelected(report.getAnswerId());
                    } else {
                        question.setSelected("");
                    }
                }
            }
            return question;
        }
        return question;
    }


}
